const { resolve } = require("path");

const Dotenv = require('dotenv-webpack')
const HtmlWebpackPlugin = require("html-webpack-plugin");
const ESLintWebpackPlugin = require("eslint-webpack-plugin");
const WebpackBar = require("webpackbar");
const CaseSensitivePathsPlugin = require('case-sensitive-paths-webpack-plugin')
const CircularDependencyPlugin = require('circular-dependency-plugin')
const NodePolyfillPlugin = require('node-polyfill-webpack-plugin')
const ForkTsCheckerWebpackPlugin = require('fork-ts-checker-webpack-plugin')
const AntdDayjsWebpackPlugin = require("antd-dayjs-webpack-plugin");
const { BundleAnalyzerPlugin } = require('webpack-bundle-analyzer')

const paths = require('./paths')
const alias = require('./alias')
const rules = require('./rules') // loader rules
const { ROOT_PATH, DOCUMENT_TITLE } = require("./constant");
const { isDev, USE_ANALYZE } = require("./env");


let dotEnv = ''
switch (process.env.BUILD_GOAL) {
  case 'development':
    dotEnv = '.env.development'
    break
  case 'production':
    dotEnv = '.env.production'
    break
  default:
    dotEnv = '.env.development'
}

const config = {
  entry: `${paths.src}/index.tsx`,
  output: {
    path: paths.dist, // 出口 文件输入到个目录
    publicPath: isDev ? '/' : './',
    // 入口文件打包输出资源命名方式
    filename: isDev ? 'scripts/[name].js' : 'scripts/[name].[contenthash:10].js',
    // 动态导入输出资源命名方式
    chunkFilename: isDev ? 'scripts/[name].chunk.js' : 'scripts/[name].[contenthash:10].chunk.js',
    assetModuleFilename: "assets/[name].[hash:10].[ext][query]", // 图片、字体等资源命名方式
    clean: true, // 打包时清空上次产物
  },
  // 解析模块规则别名
  resolve: {
    extensions: [".tsx", ".ts", ".js", ".json"], // 若没有写后缀时，依次从数组中查找相应后缀文件是否存在
    alias,
    symlinks: false,
    mainFiles: ["index"], // 可以省略的文件名
  },
  module: {
    // 将缺失的导出提示成错误而不是警告
    strictExportPresence: true,
    rules,
  },
  plugins: [
    // new Dotenv({
    //   path: resolve(__dirname, '..', dotEnv),
    // }),
    // html模板
    new HtmlWebpackPlugin({
      title: DOCUMENT_TITLE,
      template: `${paths.public}/index.html`,
      favicon: `${paths.public}/favicon.ico`,
      filename: "index.html",
      inject: "body",
    }),
    // 配置eslint
    new ESLintWebpackPlugin({
      fix: true,
      extensions: [".ts", ".tsx", ".json"],
      exclude: "node_modules",
      cache: true, // 开启eslint 缓存 第二次编译更快
      cacheLocation: resolve(ROOT_PATH, "node_modules/.cache/.eslintcache"),
    }),
    // 打包显示进度条
    new WebpackBar(),
    // 强制所有必需模块的完整路径与磁盘上实际路径的确切大小写匹配
    new CaseSensitivePathsPlugin(),
    // 检查是否有循环依赖问题
    new CircularDependencyPlugin({
      exclude: /node_modules/,
      include: /src/,
      failOnError: true,
      allowAsyncCycles: false,
      cwd: process.cwd(),
    }),
    // NodePolyfillPlugin 只有webpack 5+需要这个模块
    new NodePolyfillPlugin(),
    // 加速TypeScript类型检查（通过将其移至单独的进程） 校验ts
    new ForkTsCheckerWebpackPlugin({
      async: false,
    }),
    // 将antd中的moment.js替换为day.js
    new AntdDayjsWebpackPlugin(),
  ],
  performance: false, // 关闭性能分析，提示速度
};

// Webpack 包分析器
if (USE_ANALYZE) {
  config.plugins.push(new BundleAnalyzerPlugin())
}

module.exports = config
